package org.tailor
import com.metasieve.shoppingcart.*

class ShirtController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

	
      def list = {
			params.max = Math.min(params.max ? params.int('max') : 10, 100)
			
			def offsetValue=request.getParameter("offset")
			if(offsetValue== null){
				offsetValue=0
			}
		
			def regionList = Shirt.executeQuery("SELECT distinct S FROM Shirt S, Tailor T, Regions R WHERE  S.tailor=T.tailorID and T.regions=R.regionID  GROUP BY R.regionName")
			def shirtList = Shirt.executeQuery("SELECT distinct S FROM Shirt S, Tailor T, Regions R WHERE  S.tailor=T.tailorID and T.regions=R.regionID  ORDER BY R.regionName",[max:params.max, offset:offsetValue])
			def countShirt= Shirt.executeQuery("SELECT count(S.id) as to FROM Shirt S, Tailor T, Regions R WHERE  S.tailor=T.tailorID and T.regions=R.regionID  ORDER BY R.regionName")
			def counts
			if(countShirt.get(0) == null ) {
				counts = params.max
			}
			else{
				counts = countShirt.get(0)
				}
			[regionList:regionList, shirtList:shirtList, shirtInstanceTotal: counts]
    }

    def create = {
        def shirtInstance = new Shirt()
        shirtInstance.properties = params
        return [shirtInstance: shirtInstance]
    }
	def createOld = {
		def shirtInstance = new Shirt()
		shirtInstance.properties = params
		return [shirtInstance: shirtInstance]
	}

	def search = {
		def firstTime = params.firstTime

		if(firstTime == null || firstTime.isEmpty()) {
			def shirtName = params.shirtName
			def regionId = params.regionNameSelected
			def fabricId = params.fabricSelected
						
			String whereClause = " S.tailor=T.tailorID and T.regions=R.regionID "

			if (shirtName != null && shirtName.trim().length()>0) {
				
				whereClause = whereClause + " and S.shirtName = '" + shirtName + "'"
			}

			if (regionId != null && regionId !="0") {
				whereClause = whereClause + " and R.regionID = " + regionId
			}


			if (shirtName.trim().length()==0 && regionId == "0" && fabricId == "null") {

				params.max = Math.min(params.max ? params.int('max') : 10, 100)
				def regionList = Shirt.executeQuery("SELECT distinct S FROM Shirt S, Tailor T, Regions R WHERE " + whereClause+ " GROUP BY R.regionName")
				def shirtList = Shirt.executeQuery("SELECT distinct S FROM Shirt S, Tailor T, Regions R WHERE " + whereClause+ " ORDER BY R.regionName")
				[regionList:regionList, shirtList:shirtList, shirtInstanceTotal: shirtList.count(), shirtName:shirtName,regionId:regionId, fabricId:fabricId]

			} else {
				def regionList = Shirt.executeQuery("SELECT distinct S FROM Shirt S, Tailor T, Regions R WHERE " + whereClause+ " GROUP BY R.regionName")
				def shirtListNameRegion = Shirt.executeQuery("SELECT distinct S FROM Shirt S, Tailor T, Regions R WHERE " + whereClause)
				def shirtList = []
				if (fabricId != "null" && fabricId.trim().length()>0) {
					def shirtListFabric = Shirt.withCriteria {
						createAlias("fabric", "f")
						eq("f.id", Long.parseLong(fabricId))
					}
					shirtList = shirtListNameRegion.intersect(shirtListFabric)
				} else {
					shirtList = shirtListNameRegion
				}
				
				[regionList:regionList, shirtList:shirtList, shirtInstanceTotal: shirtList.count(), shirtName:shirtName,regionId:regionId, fabricId:fabricId]
			}
		}
	}

	
	
    def save = {
        def shirtInstance = new Shirt(params)
		shirtInstance.addToFabric(Fabric.get(params.fabric.id))
        if (shirtInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'shirt.label', default: 'Shirt'), shirtInstance.id])}"
            redirect(action: "show", id: shirtInstance.id)
        }
        else {
            render(view: "create", model: [shirtInstance: shirtInstance])
        }
    }

    def show = {
        def shirtInstance = Shirt.get(params.id)
        if (!shirtInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'shirt.label', default: 'Shirt'), params.id])}"
            redirect(action: "list")
        }
        else {
            [shirtInstance: shirtInstance]
        }
    }
	 def renderImage = {
	  def shirtInstance = Shirt.get(params.id)
		if (shirtInstance!=null) {
		   response.setContentLength(shirtInstance.designPicture.length)
		   byte[] image =shirtInstance.designPicture
		    response.outputStream.write(image)
	   }
	   else {
		   response.setContentType("image/jpeg")
		   response.getOutputStream().write("No Image".bytes)
	   }
   }
	 
    def edit = {
        def shirtInstance = Shirt.get(params.id)
        if (!shirtInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'shirt.label', default: 'Shirt'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [shirtInstance: shirtInstance]
        }
    }

    def update = {
        def shirtInstance = Shirt.get(params.id)
		def designPicture = shirtInstance.designPicture
        if (shirtInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (shirtInstance.version > version) {
                    
                    shirtInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'shirt.label', default: 'Shirt')] as Object[], "Another user has updated this Shirt while you were editing")
                    render(view: "edit", model: [shirtInstance: shirtInstance])
                    return
                }
            }
            shirtInstance.properties = params
			if(params.designPicture.getSize() == 0){
				shirtInstance.designPicture = designPicture
				}
            if (!shirtInstance.hasErrors() && shirtInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'shirt.label', default: 'Shirt'), shirtInstance.id])}"
                redirect(action: "show", id: shirtInstance.id)
            }
            else {
                render(view: "edit", model: [shirtInstance: shirtInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'shirt.label', default: 'Shirt'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def shirtInstance = Shirt.get(params.id)
        if (shirtInstance) {
            try {
                shirtInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'shirt.label', default: 'Shirt'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'shirt.label', default: 'Shirt'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'shirt.label', default: 'Shirt'), params.id])}"
            redirect(action: "list")
        }
    }
    
    
      def add = {
		def product
		if (params.class == 'class+com.metasieve.shoppingcart.ShoppingCartInterfaceTestProduct') {
			product = ShoppingCartInterfaceTestProduct.get(params.id)
		} else {
			product = Shoppable.get(params.id)
		}
		if(params.version) {
            def version = params.version.toLong()
            if(product.version > version) {
				product.errors.rejectValue("version", "shoppable.optimistic.locking.failure", message(code:"Shoppable.already.updated"))
			} else {
				product.addToShoppingCart()
			}
		} else {
			product.addToShoppingCart()
		}

		render(template:'../testShoppingCart/shoppingCartContent', plugin:'shoppingCart')
	}

    def remove = {
		def product
		if (params.class == 'class+com.metasieve.shoppingcart.ShoppingCartInterfaceTestProduct') {
			product = ShoppingCartInterfaceTestProduct.get(params.id)
		} else {
			product = Shoppable.get(params.id)
		}

		if(params.version) {
            def version = params.version.toLong()
            if(product.version > version) {
				product.errors.rejectValue("version", "shoppable.optimistic.locking.failure", message(code:"Shoppable.already.updated"))
			} else {
				product.removeFromShoppingCart()
			}
		} else {
			product.removeFromShoppingCart()
		}

		render(template:'../testShoppingCart/shoppingCartContent', plugin:'shoppingCart')
	}

	def removeAll = {
		def product
		if (params.class == 'class+com.metasieve.shoppingcart.ShoppingCartInterfaceTestProduct') {
			product = ShoppingCartInterfaceTestProduct.get(params.id)
		} else {
			product = Shoppable.get(params.id)
		}

		if(params.version) {
            def version = params.version.toLong()
            if(product.version > version) {
				product.errors.rejectValue("version", "shoppable.optimistic.locking.failure", message(code:"Shoppable.already.updated"))
			} else {
				product.removeQuantityFromShoppingCart(shoppingCartService.getQuantity(product))
			}
		} else {
			product.removeQuantityFromShoppingCart(shoppingCartService.getQuantity(product))
		}

		render(template:'../testShoppingCart/shoppingCartContent', plugin:'shoppingCart')
	}

	def checkOut = {
		def checkedOutItems = shoppingCartService.checkOut()

		render(template:'../testShoppingCart/shoppingCartContent', model:['checkedOutItems':checkedOutItems], plugin:'shoppingCart')
	}
        
            
          
    
    
    
}
